//
//  ZHLEEComposeView.swift
//  ZHLEE_Blog_Swift_Pro
//
//  Created by ZHLEEBlander on 15/10/23.
//  Copyright © 2015年 ZHLEEBlander. All rights reserved.
//

import UIKit

class ZHLEEComposeView: UIView {
    
    private lazy var sloganImage: UIImageView = {
    
        let sloganImage = UIImageView(image: UIImage(named: "compose_slogan"))
        sloganImage.centerX = self.centerX
        sloganImage.y = 100
        
        return sloganImage
    }()
    
    // MARK: -
    // MARK: -----------------方法--------------------------
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.frame = CGRectMake(0, 0, ScreenW, ScreenH)
        //添加背景图片
        let imageView = UIImageView(image: screenImage().applyLightEffect())
        
        imageView.size = size
        
        addSubview(imageView)
        
        //添加button
        addMenuButton()
        
        //添加顶部品牌的图标
        addSubview(sloganImage)
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        dismiss()
    }
    func show(){
    
        let window = UIApplication.sharedApplication().keyWindow
        
        window?.addSubview(self)
    }
    func dismiss(){
    
        removeFromSuperview()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /**
    添加菜单按钮
    */
    private func addMenuButton(){
    
        //读取plist加载button
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        
        let composeButtonInfos = NSArray(contentsOfFile: path!)
        
        let childButtonMagin = (ScreenW - 3 * Compose_Button_W) / 4
        
        for i in 0..<composeButtonInfos!.count{
        
            let button = ZHLEEComposeButton()
            
            let info = composeButtonInfos![i] as! [String: AnyObject]
            
            button.setImage(UIImage(named: info["icon"] as! String), forState: UIControlState.Normal)
            
            button.setTitle((info["title"] as! String), forState: UIControlState.Normal)
            
            let col = i % 3
            let row = i / 3
            
            button.x = CGFloat(col) * Compose_Button_W + CGFloat(col + 1) * childButtonMagin
            button.y = CGFloat(row) * Compose_Button_H
            
            addSubview(button)
        }
        
    }
    
    /**
    屏幕截图
    
    - returns: <#return value description#>
    */
    private func screenImage() -> UIImage {
    
        let window = UIApplication.sharedApplication().keyWindow
        
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(ScreenW, ScreenH), false, 1)
        
        window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: false)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image
    }

}
